package innersort.insert;

import innersort.speed.SortStrategy;

import java.util.Arrays;

/**
 * @ author : HyoJoo-W
 * @ createDate : 2021-06-03 16:33
 * @ Description :
 */
public class ShellSort implements SortStrategy
{
    public static void main(String[] args)
    {
        int[] array = {8, 9, 1, 7, 2, 3, 5, 4, 6, 0};
        shellMoveSort(array);
        System.out.println(Arrays.toString(array));
    }

    @Override
    public void sort(int[] array)
    {
        //shellSwapSort(array);
        shellMoveSort(array);
    }

    private static void shellSwapSort(int[] array)
    {
        int count = 0;
        //gap: 增量,原序列被分成gap组
        for (int gap = array.length / 2; gap > 0; gap /= 2)
        {
            //直接从 gap索引处 遍历每个分组
            for (int i = gap; i < array.length; i++)
            {
                //遍历当前分组的元素
                for (int j = i - gap; j >= 0; j -= gap)
                {
                    if (array[j] > array[j + gap])
                    {
                        int temp = array[j];
                        array[j] = array[j + gap];
                        array[j + gap] = temp;
                    }
                }
            }
            //System.out.println("希尔排序第" + (++count) + "轮后,序列为:" + Arrays.toString(array));
        }
    }

    public static void shellMoveSort(int[] array)
    {
        //gap: 增量
        for (int gap = array.length / 2; gap > 0; gap /= 2)
        {
            //从第gap个元素开始,对其所在组进行直接插入排序
            //j - gap: 前一个元素
            for (int i = gap; i < array.length; i++)
            {
                int j = i;
                int temp = array[j];
                if (array[j] < array[j - gap])
                {
                    //寻找插入位置
                    while (j - gap >= 0 && temp < array[j - gap])
                    {
                        array[j] = array[j - gap];
                        j -= gap;
                    }
                    array[j] = temp;
                }

            }
        }
    }


}
